package com.my_spring.my_spring.service;

import com.my_spring.my_spring.pojo.User;
import com.my_spring.my_spring.pojo.dto.UserDTO;
import com.my_spring.my_spring.repository.IUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service    //  配置成 springboot bean
public class UserService implements IUserService {
    @Autowired  // 自动装配 bean
    IUserRepository userRepository;

    @Override
    public User add(UserDTO user) {
        User userObj = new User();

        //  copy 属性 - 从一个对象 copy到另一个对象
        BeanUtils.copyProperties(user, userObj);

        //  调用访问类方法
        return userRepository.save(userObj);
    }

    @Override
    public User getUser(Integer id) {
        //  调用访问类方法
        return userRepository.findById(id).orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在，参数异常"); //  会在控制台打印
        });
    }

    @Override
    public User edit(UserDTO user) {
        User userObj = new User();
        BeanUtils.copyProperties(user, userObj); // 类型转换

        return userRepository.save(userObj);
    }

    @Override
    public void delete(Integer id) {
        userRepository.deleteById(id);
    }
}
